// ===================================
// 提供方法
//  doPreviewPicture 主动调用
//  like 点赞回调
//  collection 收藏回调
//  preparation 上下翻页回调
//  pageEvent 存在的图片数据跨页事件
/*!
 *图片选择模块
 * @author Sherlock 
 */
require( './style.less' );
define( [ 'require', 'jquery', 'transit', 'constants', 'message', 'imgCategory', 'h2Api', 'api', 'login' ], function( require, $ ) {

  var returnParam = {};

  var constants = require( 'constants' );
  var applicationKey = constants.applicationKey;
  var ShowTitleMessage = require( 'message' );
  var showTime = ShowTitleMessage.showTime;
  var pictureClassify = require( 'imgCategory' ).pictureClassify;
  var pictureSource = require( 'imgCategory' ).pictureSource;
  var apis = require( 'api' ).IMG_BROWSE;
  var h2Api = require( 'h2Api' );
  var me = returnParam.$selector = $( '#pictur-browse-wrap', window.top.document );
  var login = require( 'login' );

  /*图片预览点击配置*/
  var currentPageId = $( '#currentPageId', me ).val();
  var topOverflowY = $( 'body', window.top.document ).css( 'overflow-y' );

  if ( currentPageId == 'TLM001' || currentPageId == 'TLM006' || currentPageId == 'TLM028' ) {
    me.addClass( 'singleImg' );
  }
  if ( currentPageId == 'TLM028' ) {
    me.addClass( 'singleImg' );
    $( '.pic-bro-diglog .img_cz', me ).addClass( 'hide' );
  }

  ///========================
  // 事件
  me
    // 关闭预览图片
    .on( 'click', '#absl-btn-close', function() {
      returnParam.isInnerPreivew = false;
      $( this ).parent().transition( {
        opacity: 0
      }, function() {
        $( this ).hide();
        $( 'body', window.top.document ).removeClass( 'modal-open' ).css( {
          'padding-right': ''
        } );
      } );
    } )
    // 上一张
    .on( 'click', '.absl-btn-prev', function( e, fromtrigger ) {
      var $thisPic = $( '.picture .current', me );
      if ( $thisPic.index() == 0 ) {
        if ( $.isFunction( returnParam.preparation ) && !returnParam.isInnerPreivew ) {
          // 第一个参数是当前显示的图片对象
          // 第二个参数是向前或者向后 大于0是向前 小于等于0是向后
          var backResult = returnParam.preparation.call( me, $thisPic, 0 );
          if ( backResult && $.isFunction( backResult.done ) ) {
            backResult.done( function() {
              $( this ).trigger( 'click', 1 );
            }.bind( this ) );
          } else if ( backResult === 0 ) {
            ShowTitleMessage.showWarning( '已经是第一张啦', showTime );
          }
        } else {
          ShowTitleMessage.showWarning( '已经是第一张啦', showTime );
        }
        return;
      } else {
        if ( $thisPic.hasClass( 'pagePrevMark' ) && !fromtrigger ) {
          if ( $.isFunction( returnParam.pageEvent ) && !returnParam.isInnerPreivew ) {
            returnParam.pageEvent( 0 );
          }
        }
      }


      $thisPic.addClass( 'navOutPrev' );
      $thisPic.prev().addClass( 'navInPrev' );
      setTimeout( function() {
        $thisPic.removeClass( 'navOutPrev current' );
        $thisPic.prev().removeClass( 'navInPrev' ).addClass( 'current' );
      }, 0.3e3 );

      pictureData.picInfoFull.call( $thisPic.prev() );
      if ( $( '.pictur-columns .column1', me ).css( 'display' ) != 'none' ) {
        if ( $( '.ctrl-tag-recom', me ).css( 'display' ) != 'none' ) {
          pictureData.recommendPicture( $thisPic.prev() );
        }
      } else {
        pictureData.classifyPicture( $thisPic.prev() );
      }
    } )
    // 下一张
    .on( 'click', '.absl-btn-next', function( e, fromtrigger ) {
      var $thisPic = $( '.picture .current', me ),
        nextPic = $thisPic.next();

      if ( nextPic.index() == -1 ) {
        if ( $.isFunction( returnParam.preparation ) && !returnParam.isInnerPreivew ) {
          // 第一个参数是当前显示的图片对象
          // 第二个参数是向前或者向后 大于0是向前 小于等于0是向后
          var backResult = returnParam.preparation.call( me, $thisPic, 1 );
          if ( $.isFunction( backResult.done ) ) {
            backResult.done( function() {
              $( this ).trigger( 'click', 1 );
            }.bind( this ) );
          } else if ( backResult === 0 ) {
            ShowTitleMessage.showWarning( '已经是最后一张啦', showTime );
          }
        } else {
          ShowTitleMessage.showWarning( '已经是最后一张啦', showTime );
        }
        return;
      } else {
        if ( $thisPic.hasClass( 'pageNextMark' ) && !fromtrigger ) {
          if ( $.isFunction( returnParam.pageEvent ) && !returnParam.isInnerPreivew ) {
            returnParam.pageEvent( 1 );
          }
        }
      }


      $thisPic.addClass( 'navOutNext' );
      nextPic.addClass( 'navInNext' );
      setTimeout( function() {
        $thisPic.removeClass( 'navOutNext current' );
        nextPic.removeClass( 'navInNext' ).addClass( 'current' )
        /*$('.itemwrap', me).transition({
            height: nextPic.height()
        });*/
      }, 0.3e3 );

      pictureData.picInfoFull.call( nextPic );
      if ( $( '.pictur-columns .column1', me ).css( 'display' ) != 'none' ) {
        if ( $( '.ctrl-tag-recom', me ).css( 'display' ) != 'none' ) {
          pictureData.recommendPicture( $thisPic.next() );
        }
      } else {
        pictureData.classifyPicture( $thisPic.next() );
      }

    } )
    // 关闭查看原图
    .on( 'click', '#absl-btn-close2', function() {

      var $img = $( '.itemwrap>.current>img', me );
      me.css( {
        'overflow-x': 'hidden',
        'overflow-y': 'auto',
      } );

      $( '.float-srcpreivew', me ).transition( {
        opacity: 0
      }, function() {
        $( this ).hide();
        /*if (topOverflowY != 'hidden') {
        	$('body', window.top.document).css({
        		'padding-right': '',
        		'overflow': ''
        	});
        }*/
      } );
    } )
    // 查看原图
    .on( 'click', '.js_src_picture, .itemwrap img', function() {
      /*if ( topOverflowY != 'hidden' ) {
        $( 'body', window.top.document ).css( {
          'padding-right': '17px',
          'overflow': 'hidden'
        } );
      }*/
      me.css( {
        'overflow': 'hidden'
      } );
      $( "#absl-btn-close2", me ).fadeIn();
      var winHeight = $( window ).height();
      var $img = $( '.itemwrap>.current>img', me );
      var picHtml = $img.attr( 'src' );
      $( '.float-srcpreivew-img', me ).prop( 'src', picHtml );
      $( '.float-srcpreivew', me ).show().transition( {
        opacity: 1
      } );
    } )
    // 左右图片导航位置
    .on( 'scroll', function() {
      var scrollTop = $( this ).scrollTop();
      var winHeight = $( window ).height();
      $( '#absl-btn-close', me ).css( {
        top: scrollTop
      } );
      $( '.absl-btn-prev, .absl-btn-next', me ).css( {
        top: winHeight / 2 + scrollTop
      } );
    } )
    // 关闭按钮
    .on( 'scroll', '.float-srcpreivew', function() {
      $( '#absl-btn-close2', me ).css( 'top', $( this ).scrollTop() );
    } )
    // 查看右侧图片
    .on( 'click', '.pictur-columns li', function() {

      returnParam.isInnerPreivew = true;

      $( '.js_like', me ).hide();

      var self = $( this );
      self.addClass( "current" ).siblings().removeClass( "current" );
      pictureData.picInfoFull.call( self );
      var $html = self.removeAttr( 'style' );
      $( '.itemwrap>.current', me ).transition( {
        x: -600,
        opacity: 0
      }, 0.2e3, function() {
        var itemwrap = $( '.itemwrap', me ).html( self.parent().html() );
        $( '.itemwrap li img', me ).each( function() {
          $( this ).prop( 'src', constants.img02Store + $( this ).attr( 'real_src' ) );
        } );

        setTimeout( function() {
          // 暂时注释
          return;
          itemwrap.transition( {
            height: $( '.itemwrap>.current', me ).height()
          } ).find( '.current img' ).attr( 'onload', '$(this).parent().parent().transition({"height": $(this).height()})' );
        }, .2E3 );
      } );
    } )
    // 收藏图片
    .on( 'click', '.js_collection', function() {
      var liObj = $( '.itemwrap .current', me ),
        postData = {},
        imgCd = liObj.attr( 'image_id' ),
        thisImg = this;
      if ( imgCd ) {
        postData.cd = imgCd;
      } else {
        $.extend( postData, {
          url: liObj.find( '[real_src]' ).attr( 'real_src' ),
          title: liObj.attr( 'image_title' ),
          tags: ( liObj.attr( 'image_label' ) || '' ).replace( /\[|\]/g, '' ),
          publish_time: liObj.attr( 'publish_time_millis' ),
          only_collect: 1
        } );
      }
      $.ajax( {
        type: 'post',
        url: apis.DO_COLLECT_IMG,
        data: postData,
        success: function( data ) {
          data = $.parseJSON( data )
          if ( data.ret == 22100 ) {
            ShowTitleMessage.showWarning( '图片已经收藏过啦', showTime );
          } else if ( data.ret == 0 ) {

            if ( imgCd ) {
              if ( $( thisImg ).hasClass( 'icon_selected' ) ) {
                $( '.iconfont', $( thisImg, me ).removeClass( 'icon_selected' ) ) /*.removeClass('icon-collected').addClass('icon-collect')*/ ;
                $( '.text', thisImg ).text( '收藏' );
                liObj.attr( 'is_collect', 0 );
              } else {
                $( '.iconfont', $( thisImg, me ).addClass( 'icon_selected' ) ) /*.removeClass('icon-collect').addClass('icon-collected')*/ ;
                $( '.text', thisImg ).text( '已收藏' );
                liObj.attr( 'is_collect', 1 );
              }
            } else {
              if ( $( thisImg ).hasClass( 'icon_selected' ) ) {
                ShowTitleMessage.showWarning( '此类图片无法在这里删除，请前往“我的收藏”删除', showTime );
                return;
              } else {
                $( '.iconfont', $( thisImg, me ).addClass( 'icon_selected' ) ) /*.removeClass('icon-collect').addClass('icon-collected')*/ ;
                $( '.text', thisImg ).text( '已收藏' );
                liObj.attr( 'is_collect', 1 );
              }
            }
            if ( $.isFunction( returnParam.collection ) ) {
              if ( imgCd ) {
                returnParam.collection.call( me, imgCd, data.data.is_collect );
              }
            }
          }
        }
      } );

    } )
    // 点赞图片
    .on( 'click', '.js_like', function() {
      // 点赞图片
      var liObj = $( '.itemwrap .current', me ),
        imgCd = liObj.attr( 'image_id' ),
        currentLike = parseInt( liObj.attr( 'like_num' ) ),
        thisImg = this;
      if ( !imgCd ) return;
      $.ajax( {
        type: 'post',
        url: apis.DO_LIKE_IMG,
        data: {
          cd: imgCd
        },
        success: function( data ) {
          data = $.parseJSON( data );
          if ( !data.ret ) {

            if ( $( thisImg ).hasClass( 'icon_selected' ) ) {
              $( '.iconfont', $( thisImg, me ).removeClass( 'icon_selected' ) ) /*.removeClass('icon-dianzan1').addClass('icon-dianzan')*/ ;
              liObj.attr( 'is_like', 0 );
              if ( isNaN( currentLike ) ) {
                currentLike = '点赞';
              } else {
                --currentLike;
                currentLike < 0 ? 0 : currentLike;
              }
            } else {
              $( '.iconfont', $( thisImg, me ).addClass( 'icon_selected' ) ) /*.removeClass('icon-dianzan').addClass('icon-dianzan1')*/ ;
              liObj.attr( 'is_like', 1 );
              if ( isNaN( currentLike ) ) {
                currentLike = '已点赞';
              } else {
                ++currentLike;
              }
            }
            if ( currentLike > -1 ) {
              liObj.attr( 'like_num', currentLike );
            }
            $( '.text', thisImg ).text( currentLike );
            if ( $.isFunction( returnParam.like ) ) {
              if ( imgCd ) {
                returnParam.like.call( me, imgCd, data.data.is_like );
              }
            }
          }
        }
      } );
    } )
    // 标签点击
    .on( 'click', '.tags-div>button', function() {
      var tagWord = $.trim( $( this ).text() );
      if ( $( '#currentPageId', me ).val() == 'TLM020' ) {
        $( '#absl-btn-close', me ).trigger( 'click' );
        $( '#search_text' ).val( tagWord );
        $( '.search .search_btn' ).trigger( 'click' );
      } else {
        location.href = '/search/images?search_type=image&search_key=' + tagWord;
      }
    } )
    //分享
    .on( 'click', '.img_share a', function( a ) {
      var user_login = constants.userLogin;
      var $thisPic = $( '.picture .current', me );
      if ( user_login == '' ) {
        a.preventDefault();
        a.stopImmediatePropagation();
        $( '#login-modal' ).modal( 'show' );
        login.loginSuccessAndContinue = $.proxy( function() {
          $( this ).trigger( 'click' );
        }, this );

      } else {
        var _url = 'http://' + window.location.host + '/search/img_detail?picxx_cd=' + $thisPic.attr( 'image_id' );
        a.stopPropagation();
        s.img = $thisPic.children( 'img' ).attr( 'real_src' );
        s.url = _url;
        s.summary = $( '.title .title-text', me ).text() == '' ? '分享图片' : $( '.title .title-text', me ).text();
        share( a.target.className );
        a.preventDefault();
      }
    } );
  ///========================
  // 上一页下一页由{ret: 0, data: ajax} 
  var a, b, s, t = 0;
  s = {
    title: '',
  }, t = {
    jiathis: function( a, b ) {
      window.open( "http://www.jiathis.com/send/?webid=" + a + "&url=" + encodeURIComponent( b.url ) + "&summary=" + encodeURIComponent( b.summary ) + "&uid=2118247&pic=" + encodeURIComponent( b.img ) + "&appkey=" + b.appkey );
    }
  };

  function share( c ) {
    switch ( c ) {
      case "qzone":
        s.appkey = 101286682;
        t.jiathis( "qzone", s );
        break;
      case "sina":
        s.appkey = 2121870539;
        t.jiathis( "tsina", s );
        break;
        // case "weixin":
        //     createRcode("weixin", s);
        //     break;
    }
  }
  var pictureData = {
    recommendData: {},
    classifyData: {},
    classifySearch: {
      ak: applicationKey,
      page: 1,
      limit: 30,
      query: '',
      cc: ''
    },
    recommendPicture: function( current ) {
      var pic = this;
      var imgId = ( current.attr( 'image_id' ) || current.attr( 'randomStr' ) || '' ) + '',
        url = $( '>img', current ).attr( 'real_src' ),
        loadedId = $( '.pictur-columns .column1', me ).attr( 'image_id' );
      if ( loadedId == imgId ) return;

      $( '.tag-inner .column1 ul', me ).empty();
      $( '.tag-inner .column1', me ).attr( 'image_id', imgId );
      $( '.pictur-columns .column1>.gray', me ).hide();

      if ( imgId && pic.recommendData[ imgId ] ) {
        var cacheData = pic.recommendData[ imgId ];
        if ( cacheData && cacheData.length ) {
          $( '.tag-inner .column1 ul', me ).html( pic.recommendHtml( cacheData ) );
        } else {
          $( '.pictur-columns .column1>.gray', me ).show();
        }
        return;
      }
      $( '.tag-inner .column1 .spinner', me ).show();

      window.callbackFunction = function( data ) {
        var data = typeof data === 'string' ? $.parseJSON( data ) : data;
        $( '.tag-inner .column1 .spinner', me ).hide();
        if ( !data.ret ) {
          if ( imgId ) {
            pic.recommendData[ imgId ] = data.data
          }
          if ( data.data && data.data.length ) {
            $( '.tag-inner .column1 ul', me ).html( pic.recommendHtml( data.data ) );
          } else {
            $( '.pictur-columns .column1>.gray', me ).show();
          }
        } else {
          ShowTitleMessage.showWarning( data.msg || "推荐图片获取发生错误", showTime );
        }
      }
      $.ajax( {
        type: 'get',
        timeout: 600e3,
        url: apis.PICTURE_SIMILAR,
        // dataType: 'jsonp',
        data: {
          // ak: pic.classifySearch.ak,
          // iu: url,
          url: url,
        },
        jsonpCallback: 'callbackFunction',
        success: window.callbackFunction
      } );
    },
    classifyPicture: function( current, searchParam, fn ) {
      var pic = this;

      var imgId = ( current.attr( 'image_id' ) || current.attr( 'randomStr' ) || '' ) + '',
        categoryCode = current.attr( 'image_classify' ) || '',
        loadedId = $( '.pictur-columns .column2', me ).attr( 'image_id' );
      if ( loadedId == imgId ) return;

      $( '.tag-inner .column2 ul', me ).empty();
      $( '.tag-inner .column2', me ).attr( 'image_id', imgId );
      var search = $.extend( pic.classifySearch, searchParam, {
        cc: categoryCode
      } );
      $( '.pictur-columns .column1>.gray', me ).hide();
      if ( imgId && pic.classifyData[ imgId ] ) {
        var cacheData = pic.classifyData[ imgId ];
        if ( cacheData && cacheData.length ) {
          $( '.tag-inner .column2 ul', me ).html( pic.recommendHtml( cacheData ) );
        } else {
          $( '.pictur-columns .column2>.gray', me ).show();
        }
        return;
      }

      $( '.tag-inner .column2 .spinner', me ).show();

      window.callbackFunction2 = function( data ) {
        $( '.tag-inner .column2 .spinner', me ).hide();
        if ( !data.ret ) {
          if ( imgId ) {
            pic.classifyData[ imgId ] = data.data;
          }

          if ( data.data && data.data.length ) {
            $( '.tag-inner .column2 ul', me ).html( pic.recommendHtml( data.data ) );
          } else {
            $( '.pictur-columns .column2>.gray', me ).show();
          }
        } else {
          ShowTitleMessage.showWarning( data.msg || "推荐图片获取发生错误", showTime );
        }
        if ( $.isFunction( fn ) ) {
          fn();
        }
      }
      $.ajax( {
        type: 'get',
        timeout: 600e3,
        url: h2Api.IMG_QUERY,
        dataType: 'jsonp',
        data: search,
        jsonpCallback: 'callbackFunction2',
        success: window.callbackFunction2
      } );
    },
    recommendHtml: function( arr ) {
      var html = '';
      for ( i in arr ) {
        var img = arr[ i ];
        html += '<li image_title="' + ( img.title || '' ) + '" image_classify="' + img.category_code + '" image_time="' + new Date( img.publish_time_millis ).format( 'yyyy-MM-dd' ) + '" image_label="' + ( img.tags || '' ) + '" publish_time_millis="' + img.publish_time_millis + '" randomStr="' + ( new Date().getTime() + "" + parseInt( Math.random() * 3e3 ) ) + '">';
        html += '<div class="collect-like">';
        html += '<button type="button" class="js_collection"><span class="iconfont icon-collect"></span>收藏</button>';
        //html += '<button type="button" like-event="picture"><span class="iconfont icon-dianzan"></span><span class="like-count">100000+</span></button>';
        html += '</div>';
        html += '<img src="' + constants.surpportHostName + '/timthumb.php?src=' + img.img_url + '" real_src="' + img.img_url + '" onerror="$(this).parent().remove();"/>';
        html += '</li>';
      }

      return html;
    },
    classifyHtml: function( arr ) {
      return this.recommendHtml( arr );
    },
    picInfoFull: function() {
      var image_title = $( this ).attr( 'image_title' ) || '暂无标题',
        image_classify = $( this ).attr( 'image_classify' ),
        image_time = $( this ).attr( 'image_time' ),
        image_label = $( this ).attr( 'image_label' ) || '',
        image_label = image_label.replace( /\[|\]/g, '' ).split( ',' ),
        image_num = $( this ).attr( 'image-num' ),
        isCollected = $( this ).attr( 'is_collect' ),
        isLike = $( this ).attr( 'is_like' ),
        likeNum = parseInt( $( this ).attr( 'like_num' ) ),
        source = $( this ).attr( 'source' )
      var html = '';
      for ( i in image_label ) {
        if ( image_label[ i ] && i < 5 ) {
          html += '<button type="button">' + image_label[ i ] + '</button>';
        }
      }
      $( '.tags-div', me ).html( html || '暂无标签' );
      $( '.title-text', me ).text( image_title ).prop( 'title', image_title );
      //$('.this-count', me).text(parseInt(image_num) + 1);
      $( '.js_date_img', me ).text( image_time );
      $( '.cate-value', me ).text( image_classify );
      $( '.tag-column-choose .classify', me ).text( pictureClassify[ image_classify ] || '其他' );
      $( '.js_category_text', me ).text( pictureClassify[ image_classify ] || '其他' );
      $( '.from-value', me ).text( pictureSource[ source ] || '未知' );

      if ( isCollected == 1 ) {
        $( '.iconfont', $( '.js_collection', me ).addClass( 'icon_selected' ) ) /*.removeClass('icon-collect').addClass('icon-collected')*/ ;
        $( '.js_collection .text', me ).text( '已收藏' );
      } else {
        $( '.iconfont', $( '.js_collection', me ).removeClass( 'icon_selected' ) ) /*.removeClass('icon-collected').addClass('icon-collect')*/ ;
        $( '.js_collection .text', me ).text( '收藏' );
      }

      if ( isLike == 1 ) {
        likeNum = !isNaN( likeNum ) ? likeNum : '已点赞';
        $( '.iconfont', $( '.js_like', me ).addClass( 'icon_selected' ) ) /*.removeClass('icon-dianzan').addClass('icon-dianzan1')*/ ;
      } else {
        likeNum = !isNaN( likeNum ) ? likeNum : '点赞';
        $( '.iconfont', $( '.js_like', me ).removeClass( 'icon_selected' ) ) /*.removeClass('icon-dianzan1').addClass('icon-dianzan')*/ ;
      }
      $( '.js_like .text', me ).text( likeNum );
    }
  }

  var dataFactory = {
    htmlBuild: function( dataArr ) {
      var html = '';
      for ( var i in dataArr ) {
        var json = dataArr[ i ];
        html += '<li image_title="' + ( json.title || '' ) +
          '" image_classify="' + json.category_code +
          '" image_time="' + json.publish_time +
          '" image_label="' + ( json.tags || '' ) +
          '" image_id="' + json.image_id +
          '" is_collect="' + json.is_collect +
          '" is_like="' + json.is_like +
          '" like_num="' + json.like_num +
          '" source="' + json.source + '"><img src="' + constants.img02Store + json.img_url +
          '" real_src="' + json.img_url + '"></li>';
      }

      return html;
    }
  };

  // 开始预览图片
  /**
   * title
   * category_code
   * publish_time
   * image_id
   * is_collect
   * is_like
   * like_num
   * source
   * tags
   * img_url
   */
  returnParam.doPreviewPicture = function( preivewArray, before_or_after, currentIndex ) {
    var dataHtml = dataFactory.htmlBuild( preivewArray );
    if ( dataHtml ) {
      dataHtml = $( dataHtml );
      $( dataHtml ).eq( dataHtml.length - 1 ).addClass( 'pageNextMark' );
      $( dataHtml ).eq( 0 ).addClass( 'pagePrevMark' );
    }
    if ( before_or_after === undefined || before_or_after === null ) {
      $( '.itemwrap', me ).html( dataHtml );
    } else if ( before_or_after > 0 ) {
      $( '.itemwrap', me ).append( dataHtml );
    } else {
      $( '.itemwrap', me ).prepend( dataHtml );
    }

    currentIndex > -1 && $( '.itemwrap>li', me ).eq( currentIndex ).addClass( 'current' ).siblings().removeClass( 'current' );

    this._show();
  }


  returnParam._show = function() {
    $( 'body', window.top.document ).addClass( 'modal-open' ).css( {
      'padding-right': '17px',
    } );
    me.show().transition( {
      opacity: 1
    }, .5e3, function() {
      var current = $( '.itemwrap>.current', me );
      if ( $( '.ctrl-tag-recom', me ).css( 'display' ) != 'none' ) {
        pictureData.recommendPicture( current );
      }

      pictureData.picInfoFull.call( current );
    } );
    $( '.js_like', me ).show();
  }


  return returnParam;

} );
